<template>
  <!-- 添加或修改入库管理对话框 -->
  <el-dialog v-dialogDrag v-dialogDragWidth :title="title" :visible.sync="open" width="900px" append-to-body :close-on-click-modal=false>
    <el-form ref="form" :model="form" :rules="rules"  label-width="80px">
      <el-alert v-show="form.oaDictConfirmStatus != 'editing'"
                style="margin-bottom: 15px;"
                :title="form.latestTaskInfo"
                type="info"
                :closable="false"
                effect="dark"
      >
      </el-alert>
      <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
        <div slot="header" class="clearfix">
          <span><b>单据信息</b></span>
          <el-tooltip content="显示 / 隐藏" placement="top" style="float: right; padding: 3px 0">
            <el-switch
              v-model="fold_form_order"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value="false"
              inactive-value="true">
            </el-switch>
          </el-tooltip>
        </div>
        <div v-show="fold_form_order== 'false'">
          <el-row>
            <el-col :span="24">
              <el-form-item label="采购申请" prop="fkPmsRequestUuid" v-show="this.wmsDictStockInType=='1'">
                <el-input v-model="form.fkPmsRequestUuid" v-show="false"/>
                <el-input placeholder="请点击右侧按钮选择采购申请" readOnly="true"
                          v-model="form.selectedRequest" class="input-with-select"
                          :style="{width: '100%'}">
                  <el-button type="info" plain
                             @click="dialog_show_request"
                             slot="append" icon="el-icon-search"
                  ></el-button>
                </el-input>
              </el-form-item>

              <el-form-item label="订单信息" prop="fkOrderUuid" v-show="this.wmsDictStockInType=='0'">
                <el-input v-model="form.fkOrderUuid" v-show="false"/>
                <el-input placeholder="请点击右侧按钮选择订单" readOnly="true" v-model="form.selectedOrder" class="input-with-select"
                          :style="{width: '100%'}">
                  <el-button type="info" plain
                             @click="dialog_show_selectOrder"
                             slot="append" icon="el-icon-search"
                  ></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>

            <el-col :span="12">
              <el-form-item label="单据编号" prop="docNum">
                <el-input v-model="form.docNum" placeholder="请输入单据编号" clearable :style="{width: '100%'}"
                           />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="单据时间" prop="docDt">
                <el-date-picker clearable
                                v-model="form.docDt"
                                type="datetime"
                                clearable
                                value-format="yyyy-MM-dd HH:mm"
                                placeholder="选择单据日期"
                                :style="{width: '100%'}"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="仓库" prop="fkStockUuid">
                <el-input v-model="form.fkStockUuid" v-show="false"/>
                <el-input placeholder="请点击右侧按钮选择仓库" readOnly="true" v-model="form.selectedStock" class="input-with-select"
                          :style="{width: '100%'}">
                  <el-button type="info" plain
                             @click="dialog_show_stock"
                             slot="append" icon="el-icon-search"
                  ></el-button>
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="保管员" prop="fkAttentionUserId">
                <el-input v-model="form.fkAttentionUserId" v-show="false"/>
                <el-input placeholder="请选择保管员"
                          readOnly="true"
                          v-model="form.userNameStockIn"
                          class="input-with-select"
                          :style="{width: '100%'}"
                >
                  <el-button
                    @click="showDialog_selectAttentionUser(form)"
                    slot="append" icon="el-icon-search"
                  ></el-button>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="供应商" prop="fkSupplierUuid">
                <el-select
                  filterable
                  v-model="form.fkSupplierUuid"
                  placeholder="请选择供应商名称"
                  clearable
                  :style="{width: '100%'}" >
                  <el-option
                    v-for="item in supplierNameOptions"
                    :key="item.supplierUuid"
                    :label="item.supplierName"
                    :value="item.supplierUuid"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="docNote">
                <el-input v-model="form.docNote" type="textarea"
                          autosize placeholder="请输入备注"
                          :style="{width: '100%'}"
                />
              </el-form-item>
            </el-col>
          </el-row>

        </div>
      </el-card>
      <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
        <div slot="header" class="clearfix">
          <span><b>单据明细</b></span>
        </div>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini"
                       @click="handleAddWmsStockInDetails"
                       :disabled="form.oaDictConfirmStatus != 'editing'">添加
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini"
                       @click="handleDeleteWmsStockInDetails"
                       :disabled="form.oaDictConfirmStatus != 'editing'">删除
            </el-button>
          </el-col>
        </el-row>
        <el-table :data="wmsStockInDetailsList" :row-class-name="rowWmsStockInDetailsIndex"
                  @selection-change="handleWmsStockInDetailsSelectionChange" ref="wmsStockInDetails">
          <el-table-column type="selection" width="50" align="center"/>
<!--          <el-table-column label="排序序号" prop="orderNum" align="center" width="100px">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.orderNum" placeholder="请输入排序序号"-->
<!--                        />-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column
            label="序号"
            type="index"
            width="50"
            align="center">
            <template scope="scope">
              <span>{{scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column label="物料名称" prop="itemName" width="300px" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fkItemUuid" v-show="false"/>
              <el-input placeholder="请选择物料名称"
                        readOnly="true"
                        v-model="scope.row.itemName"
                        class="input-with-select"
              >
                <el-button @click="dialog_show_selectItem(scope)"
                           slot="append" icon="el-icon-search"

                ></el-button>
              </el-input>
            </template>
          </el-table-column>


          <el-table-column label="仓位名称" prop="fkStockPosUuid" width="240px" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.fkStockPosUuid" v-show="false"/>
              <el-input placeholder="请选择仓位名称" readOnly="true" v-model="scope.row.stockPosNameDetail"
                        class="input-with-select">
                <el-button @click="dialog_show_stockPosition(scope)" slot="append" icon="el-icon-search"
                ></el-button>
              </el-input>
            </template>
          </el-table-column>


          <el-table-column label="数量" prop="differentQty" align="center" width="120">
            <template slot-scope="scope">
              <el-input v-model="scope.row.differentQty" placeholder="请输入数量"
                        @input="inputChange(scope)"/>
            </template>
          </el-table-column>

          <el-table-column label="计量单位" prop="measuringUnit" width="180" align="center">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.measuringUnit"
                placeholder="请选择"
                style="width: 150px"
              >
                <el-option
                  v-for="dict in orderUnitOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </template>
          </el-table-column>


          <el-table-column label="物料单价" prop="itemPrice" align="center" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.itemPrice" placeholder="请输入物料单价"
                         @input="inputChange(scope)"/>
            </template>
          </el-table-column>

          <el-table-column label="金额" prop="totalAmount" align="center" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.totalAmount"
                         />
            </template>
          </el-table-column>

        </el-table>
      </el-card>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm" :disabled="form.oaDictConfirmStatus != 'editing'">确 定</el-button>
      <el-button type="warning" @click="submitForm('waiting')" :disabled="form.oaDictConfirmStatus != 'editing'">提交待审
      </el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!--组件内引用的组件-->
    <select-request ref="component_selectRequest" @ok="selectRequest_done"/>
    <select-order ref="component_selectOrder" @ok="selectOrder_done"/>
    <select-user ref="component_selectAttentionUser" @ok="selectAttentionUser_done" />
    <select-item ref="component_selectItem" @ok="selectItem_done" />
    <select-stock ref="component_selectStock" @ok="selectStock_done" />
    <select-stockPos ref="component_selectStockPos" @ok="selectStockPosition_done" />


  </el-dialog>
</template>
<script>
  import selectItem from "../../wms/wmsItems/selectItem";
  import {listStockIn, getStockIn} from "@/api/wms/stockIn";
  import selectOrder from "../../crm/crmOrders/selectOrder";
  import selectStock from "../../wms/stock/selectStock";
  import selectStockPos from "../../wms/stockPosition/selectStockPosition";
  import { addStockIn, updateStockIn} from "@/api/wms/stockIn";
  import {listRequestDetail} from "@/api/pms/requestDetails";
  import selectRequest from "../../wms/stockIn/selectRequest";
  import {newDocNum} from "@/api/oa/docNum";
  import { parseTime } from '@/utils/ruoyi';
  import selectUser from "../../comn/userGroup/selectUser";
  import {listOrderDetails} from "../../../api/crm/crmOrders";
  import { listSupplier } from "@/api/comn/supplier";

  export default {
    name: "StockIn",
    dicts: ['wms_dict_warehouse', 'oa_dict_confirm_status', 'wms_dict_stock_in_type'],
    components:{ selectRequest,selectOrder ,selectUser,selectItem,selectStock,selectStockPos},
    data() {
      return {
        stockInUuid:'',
        wmsDictStockInType:'',
        oaDictConfirmStatus:'',
        fold_form_order: 'false',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedWmsStockInDetails: [],
        supplierNameOptions: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        inventoryUserNameList: [],
        orderUnitOptions: [],
        // 总条数
        total: 0,
        // 入库管理表格数据
        stockInList: [],
        // 入库单明细表格数据
        wmsStockInDetailsList: [],
        list: [],
        docTitle: null,
        docNum: null,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          wmsDictWarehouse: null,
          fkAttentionUserId: null,
          docNum: null,
          docDt: null,
          userNameStockIn: null,
          fkPmsRequestUuid: null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          docNum: [
            {required: true, message: "请输入单据编号", trigger: "change"}
          ],
          docDt: [
            {required: true, message: "请选择单据时间", trigger: "change"}
          ],
          fkAttentionUserId: [
            {required: true, message: "请选择经办人", trigger: "change"}
          ],
          wmsDictWarehouse: [
            {required: true, message: "请选择仓库", trigger: "change"}
          ],
          fkStockUuid: [
            {required: true, message: "请选择仓库", trigger: "change"}
          ],
          fkStockPosUuid: [
            {required: true, message: "请选择仓位", trigger: "change"}
          ],
        },

      };
    },
    created() {
      this.getList()
      /**获取计量单位字典数据*/
      this.getDicts("wms_dict_measuring_unit").then(response => {
        this.orderUnitOptions = response.data;
        console.log(this.orderUnitOptions)
      });
    },
    methods: {

      inputChange(scope){
        scope.row.totalAmount = scope.row.differentQty*scope.row.itemPrice
      },

      /** 查询入库管理列表 */
      getList() {
        listStockIn(this.queryParams).then(response => {
          this.stockInList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
        listSupplier(this.queryParams).then(response => {
          this.supplierNameOptions = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          stockInUuid: null,
          fkAttentionUserId: null,
          userNameStockIn: null,
          fkPmsRequestUuid: null,
          fkOrderUuid: null,
          wmsDictStockInType: '1',
          docDt: parseTime(Date.now(), '{y}-{m}-{d} {h}:{i}'),
          oaDictConfirmStatus: null,
          selectedOrder: null,
          selectedStock: null,
          fkStockUuid: null,
          docTitle: null,
          docNum: null,
          stockNameDetail: null,
          docTitleOrder: null,
          docNumOrder: null,
          docTitleRequest: null,
          docNumRequest: null,
          docDtRequest: null,
          selectedStockPos: null,
          fkStockPosUuid: null,
          nickNameRequest: null,
          stockPosCodeDetail: null,
          stockCodeDetail: null,
          stockPosNameDetail: null,
         };
        this.wmsStockInDetailsList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      dialog_show_stockIn() {
        this.reset();


        this.form.oaDictConfirmStatus = 'editing'

        this.open = true;
        if(this.wmsDictStockInType == '1'){
          newDocNum({preCode: 'CGRK-', len: 12}).then(response => {
            this.form.docNum = response.msg
          })
          this.title = "新增采购入库单";
        }else if(this.wmsDictStockInType == '0'){
          newDocNum({preCode: 'CPRK-', len: 12}).then(response => {
            this.form.docNum = response.msg
          })
          this.title = "新增产品入库单";
        }else if(this.wmsDictStockInType == '2'){
          newDocNum({preCode: 'QTRK-', len: 12}).then(response => {
            this.form.docNum = response.msg
          })
          this.title = "新增其他入库单";
        }else if(this.wmsDictStockInType == '3'){
          newDocNum({preCode: 'CSRK-', len: 12}).then(response => {
            this.form.docNum = response.msg
          })
          this.title = "新增初始化入库单";
        }else if(this.wmsDictStockInType == '4'){
          newDocNum({preCode: 'SCTL-', len: 12}).then(response => {
            this.form.docNum = response.msg
          })
          this.title = "新增生产退料单";
        }
      },
      dialog_show_update(){
        this.reset();
        getStockIn(this.stockInUuid).then(response => {
            console.log(response)
            this.form = response.data;

          this.wmsStockInDetailsList = response.data.wmsStockInDetailsList
          console.log(this.wmsStockInDetailsList[0].stockNameDetail)

          this.form.selectedStock = this.wmsStockInDetailsList[0].stockNameDetail
          this.form.selectedStockPos = this.wmsStockInDetailsList[0].stockPosNameDetail
          if(this.oaDictConfirmStatus!='editing'||this.oaDictConfirmStatus!='reject'||this.oaDictConfirmStatus!='editing'||this.oaDictConfirmStatus!='reject'){
            this.form.latestTaskInfo='💡 该条记录审核状态为'+
              this.selectDictLabel(this.dict.type.oa_dict_confirm_status, this.oaDictConfirmStatus||this.oaDictConfirmStatus)+'状态'+','+'不能修改'
          }

          this.open = true;
          if(this.wmsDictStockInType == '1'){
            this.form.selectedRequest = `单据编号：${this.form.docNumRequest},申请人：${this.form.nickNameRequest},申请时间：${this.form.docDtRequest}`
            this.title = "修改采购入库单";
          }else if(this.wmsDictStockInType == '0'){
            this.form.selectedOrder = `销售号：${this.form.docNumOrder}`
            this.title = "修改产品入库单";
          }else if(this.wmsDictStockInType == '2') {
              this.title = "修改其他入库单";
          }else if(this.wmsDictStockInType == '3'){
            this.title = "修改初始化入库单";
          }else if(this.wmsDictStockInType == '4'){
            this.title = "修改生产退料单";
          }else if(this.wmsDictStockInType == '8'){
            this.title = "修改盘盈入库单";
          }
        });
      },

      // 完成：选择其他入库
      stockIn_done(other) {
        this.open = false;
        this.$emit("ok", other );
      },

      /** 提交按钮 */
      submitForm(confirmStatus) {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(confirmStatus=='waiting') this.form.oaDictConfirmStatus = confirmStatus
            this.form.wmsStockInDetailsList = this.wmsStockInDetailsList;
            if (this.form.stockInUuid != null) {
              updateStockIn(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.$emit("ok", null );
              });
            } else {
              this.form.wmsDictStockInType = this.wmsDictStockInType
              console.log(this.form)
              addStockIn(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.$emit("ok", null );
              });
            }
          }
        });
      },
      /** 入库单明细序号 */
      rowWmsStockInDetailsIndex({row, rowIndex}) {
        row.index = rowIndex + 1;
      },
      /** 入库单明细添加按钮操作 */
      handleAddWmsStockInDetails() {
        let obj = {};
        obj.orderNum = "1";
        obj.itemName = "";
        obj.itemNum = "";
        obj.fkItemUuid = "";
        obj.stockInQty = "";
        obj.selectItemName="";
        obj.wmsDictMeasuringUnit = "";
        obj.fkStockPosUuid = "";
        obj.stockPosNameDetail = "";
        obj.differentQty = "";
        obj.itemPrice = "";
        obj.totalAmount= "";
        this.wmsStockInDetailsList.push(obj);
      },
      /** 入库单明细删除按钮操作 */
      handleDeleteWmsStockInDetails() {
        if (this.checkedWmsStockInDetails.length == 0) {
          this.$modal.msgError("请先选择要删除的入库单明细数据");
        } else {
          const wmsStockInDetailsList = this.wmsStockInDetailsList;
          const checkedWmsStockInDetails = this.checkedWmsStockInDetails;
          this.wmsStockInDetailsList = wmsStockInDetailsList.filter(function (item) {
            return checkedWmsStockInDetails.indexOf(item.index) == -1
          });
        }
      },
      /** 复选框选中数据 */
      handleWmsStockInDetailsSelectionChange(selection) {
        this.checkedWmsStockInDetails = selection.map(item => item.index)
      },

      /** 对话框：显示 = 采购申请 */
      dialog_show_request() {
        this.$refs.component_selectRequest.dialog_show_request();
      },

      /**完成：选择采购申请*/
      selectRequest_done(request) {
        this.queryParams.fkRequestUuid = request.requestUuid;
        listRequestDetail(this.queryParams).then(response => {
          this.wmsStockInDetailsList = response.rows;
          console.log(this.wmsStockInDetailsList)
          this.total = response.total;
          this.loading = false;
        });
        this.form.fkPmsRequestUuid = request.requestUuid
        this.form.selectedRequest = `单据编号：${request.docNum}`
      },

      /** 显示对话框：选择订单 */
      dialog_show_selectOrder() {
        this.$refs.component_selectOrder.dialog_show_selectOrder();
      },
      /** 选择订单明细完成 */
      selectOrder_done(user) {
        console.log(user)
        this.queryParams.orderUuid = user.row.orderUuid
        console.log( this.queryParams.orderUuid)
        listOrderDetails(this.queryParams).then(response => {
          console.log(response)
          this.wmsStockInDetailsList = response.rows;
        });
        this.form.fkOrderUuid = user.row.orderUuid;
        this.form.selectedOrder =
          `订单编号：${user.row.docNum}`;
      },


      /** 选择车间任务经办人 */
      showDialog_selectAttentionUser(form) {
        this.currentForm = form
        // this.$refs.component_selectTaskAttentionUserName.userGroup = 'worker';
        this.$refs.component_selectAttentionUser.show();
      },
      /** 选择车间任务经办人 - 完成 */
      selectAttentionUser_done(user) {
        console.log(user)
        this.currentForm.fkAttentionUserId = user.userId
        this.currentForm.userNameStockIn = user.nickName
      },




      /** 显示对话框：选择物料 */
      dialog_show_selectItem(scope) {
        console.log(scope)
        this.requestDetails_currRowScope = scope
        this.$refs.component_selectItem.dialog_show_selectItem();
      },

      /** 完成：选择物料*/
      selectItem_done(item) {
        this.requestDetails_currRowScope.row.fkItemUuid = item.itemUuid
        this.requestDetails_currRowScope.row.itemName = item.itemName
        this.requestDetails_currRowScope.row.measuringUnit = item.wmsDictMeasuringUnit
      },

      /** 显示对话框：选择仓库 */
      dialog_show_stock() {
        this.$refs.component_selectStock.dialog_show_stock();
      },

      /** 完成：选择仓库*/
      selectStock_done(stock) {
        console.log(stock)
        this.form.fkStockUuid = stock.stockUuid
        this.form.selectedStock = stock.stockName
      },

      /** 显示对话框：选择仓位*/
      dialog_show_stockPosition(scope) {
        console.log(scope)
        this.stockInDetails_currRowScope = scope
        this.$refs.component_selectStockPos.dialog_show_stockPosition();
      },

      /** 完成：选择仓位*/
      selectStockPosition_done(stock) {
        console.log(stock)
        this.stockInDetails_currRowScope.row.fkStockPosUuid = stock.stockPosUuid
        this.stockInDetails_currRowScope.row.stockPosNameDetail = stock.stockPosName
      },


    }
  };
</script>
